package com.lagou.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.security.auth.login.Configuration;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @program: spring_transfer
 * @description:
 * @author: Mr.Wang
 * @create: 2020-12-16 10:20
 **/
@Component
public class ConnectionUtils {

	@Autowired
	private DataSource dataSource;
	private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

	public Connection getConnection(){
		Connection connection = threadLocal.get();
		if(connection == null){
			try {
				connection = dataSource.getConnection();
				threadLocal.set(connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return connection;

	}

	public void removeConnection(){
		threadLocal.remove();
	}
}
